using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class CreateDepartmentCommandHandler : IRequestHandler<CreateDepartmentCommand, DepartmentDto>
	{
		private readonly IBaseRepository<Department> _repository;

		public CreateDepartmentCommandHandler(IBaseRepository<Department> repository)
		{
			_repository = repository;
		}

		public async Task<DepartmentDto> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
		{
			var entity = new Department
			{
				DepartmentId = YitIdHelper.NextId(),
				Name = request.Name,
				Address = request.Address,
				RegistrationFee = request.RegistrationFee,
				ParentDepartmentId = request.ParentDepartmentId,
				IsKeyDepartment = request.IsKeyDepartment,
				IsEmergencyAvailable = request.IsEmergencyAvailable,
				BedCount = request.BedCount,
				CreatedAt = DateTime.Now,
				UpdatedAt = DateTime.Now
			};
			await _repository.InsertAsync(entity);
			return new DepartmentDto
			{
				DepartmentId = entity.DepartmentId,
				Name = entity.Name,
				Address = entity.Address,
				RegistrationFee = entity.RegistrationFee,
				ParentDepartmentId = entity.ParentDepartmentId,
				IsKeyDepartment = entity.IsKeyDepartment,
				IsEmergencyAvailable = entity.IsEmergencyAvailable,
				BedCount = entity.BedCount,
				CreatedAt = entity.CreatedAt,
				UpdatedAt = entity.UpdatedAt
			};
		}
	}
}
